<template>
  <div class="categories-view">
    <el-card>  
      <!-- 主分类导航 -->
      <el-menu 
        mode="horizontal"
        :default-active="activeMainCategory"
        @select="handleMainCategorySelect"
        class="main-categories-menu"
      >
        <el-menu-item 
          v-for="mainCategory in mainCategories" 
          :key="mainCategory.categoryId" 
          :index="mainCategory.categoryId.toString()"
        >
          {{ mainCategory.categoryName }}
        </el-menu-item>
      </el-menu>

      <!-- 子分类展示区 -->
      <div v-if="activeMainCategory && !showContentList" class="subcategories-container">
        <el-row :gutter="20">
          <el-col
            v-for="subCategory in subCategories"
            :key="subCategory.categoryId"
            :xs="12"
            :sm="8"
            :md="6"
            :lg="4"
          >
            <el-card
              shadow="hover"
              class="category-card"
              @click="goToCategory(subCategory)"
            >
              <div class="category-icon">
                <i :class="getCategoryIcon(subCategory.categoryName)" />
              </div>
              <h3>{{ subCategory.categoryName }}</h3>
              <p class="count">{{ subCategory.contentCount || 0 }}篇内容</p>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 内容列表展示区 -->
      <div v-if="showContentList" class="content-list-container">
        <el-button 
          type="text" 
          icon="el-icon-arrow-left" 
          @click="goBackToCategories"
          class="back-button"
        >
          返回分类
        </el-button>
        
        <div v-if="contents.length === 0" class="no-content">
          <el-empty description="该分类下暂无内容" />
        </div>
        
        <div class="content-list">
          <ContentCard
            v-for="item in contents"
            :key="item.contentId"
            :content="{
              id: item.contentId,
              title: item.title,
              summary: item.summary,
              author: item.username,
              publishTime: formatDate(item.publishTime),
              likeCount: item.likeCount || 0,
              commentCount: item.commentCount || 0,
              isLiked: item.isLiked || false,
              categoryName: item.categoryName || selectedCategory?.categoryName,
              readCount: item.readCount || 0
            }"
            @like="handleLike"
            @click="handleCardClick(item.contentId)" 
            style="cursor: pointer;" 
          />
        </div>
        
        <el-pagination
          v-if="total > pageSize"
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
          class="pagination"
        />
      </div>

      <!-- 无子分类时的提示 -->
      <div v-if="activeMainCategory && subCategories.length === 0 && !showContentList" class="no-subcategories">
        <el-empty description="该分类下暂无子分类" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue'
import { getContentByCategoryId } from '@/api/contents'
import ContentCard from '@/components/ContentCard.vue'
import axios from '@/utils/request'
import { useRouter } from 'vue-router'

export default {
  components: {
    ContentCard
  },
  setup() {
    const router = useRouter()
    return { router }
  },
  data() {
    return {
      categories: [],
      activeMainCategory: null,
      contentCounts: {},
      showContentList: false,
      selectedCategory: null,
      contents: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  computed: {
    mainCategories() {
      return this.categories.filter(cat => cat.parentId === null)
    },
    subCategories() {
      return this.categories.filter(cat => cat.parentId === parseInt(this.activeMainCategory))
    },
    currentMainCategoryName() {
      const mainCat = this.mainCategories.find(cat => cat.categoryId === parseInt(this.activeMainCategory))
      return mainCat ? mainCat.categoryName : ''
    }
  },
  mounted() {
    this.getCategories()
  },
  methods: {
    async getCategories() {
      try {
        const response = await axios.get('/category/browse')
        if (response.data.code === 200) {
          this.categories = response.data.data
          if (this.mainCategories.length > 0) {
            this.activeMainCategory = this.mainCategories[0].categoryId.toString()
          }
          await this.getContentCounts()
        } else {
          this.$message.error('获取分类失败')
        }
      } catch (error) {
        this.$message.error('请求分类数据出错')
        console.error(error)
      }
    },
    
    async getContentCounts() {
      try {
        const response = await axios.get('/category/content-counts')
        if (response.data.code === 200) {
          const contentCountsMap = {}
          response.data.data.forEach(item => {
            contentCountsMap[item.category_id] = item.content_counts
          })

          this.categories = this.categories.map(category => ({
            ...category,
            contentCount: contentCountsMap[category.categoryId] || 0
          }))
        }
      } catch (error) {
        console.error('获取内容数量失败:', error)
      }
    },
    
    handleMainCategorySelect(index) {
      this.activeMainCategory = index
      this.showContentList = false
    },
    
    getCategoryIcon(categoryName) {
      const iconMap = {
        '科技': 'el-icon-cpu',
        '娱乐': 'el-icon-video-camera',
        '体育': 'el-icon-basketball',
        '人工智能': 'el-icon-ai',
        '区块链': 'el-icon-link',
        '电影': 'el-icon-film',
        '音乐': 'el-icon-headset',
        '足球': 'el-icon-soccer',
        '篮球': 'el-icon-basketball',
        '生活': 'el-icon-house',
        '美食': 'el-icon-fork-spoon',
        '旅游': 'el-icon-place',
        '财经': 'el-icon-money',
        '股票': 'el-icon-trend-charts',
        '基金': 'el-icon-bank-card',
        '教育': 'el-icon-notebook',
        '语言学习': 'el-icon-chat-line-round',
        '考试': 'el-icon-document',
        '健康': 'el-icon-first-aid-kit',
        '健身': 'el-icon-bicycle'
      }
      
      return iconMap[categoryName] || 'el-icon-folder-opened'
    },
    
    async goToCategory(category) {
      this.selectedCategory = category
      this.showContentList = true
      this.currentPage = 1
      await this.loadContents()
    },
    
    goBackToCategories() {
      this.showContentList = false
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    },
    
    async loadContents() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        const response = await getContentByCategoryId(this.selectedCategory.categoryId, params)
        
        if (response.data.code === 200) {
          this.contents = response.data.data.records
          this.total = response.data.data.total
          this.currentPage = response.data.data.current
        } else {
          this.$message.error(response.data.message || '获取内容列表失败')
        }
      } catch (error) {
        console.error('请求出错:', error)
        this.$message.error('网络错误，请稍后重试')
      }
    },
    
    async handlePageChange(page) {
      this.currentPage = page
      await this.loadContents()
    },
    
    handleCardClick(contentId) {
      this.router.push(`/content/${contentId}`)
    },
    
    async handleLike(contentId) {
      try {
        const response = await axios.post('/content/like', { contentId })
        if (response.data.code === 200) {
          const index = this.contents.findIndex(item => item.contentId === contentId)
          if (index !== -1) {
            this.contents[index].isLiked = !this.contents[index].isLiked
            this.contents[index].likeCount += this.contents[index].isLiked ? 1 : -1
          }
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    }
  }
}
</script>

<style scoped>
.categories-view {
  flex: 1;
  padding: 20px;
}

.main-categories-menu {
  margin-bottom: 20px;
  border-right: none;
}

.subcategories-container {
  margin-top: 30px;
  padding: 20px 0;
  border-top: 1px solid var(--el-border-color-light);
}

.no-subcategories {
  margin-top: 30px;
  padding: 40px 0;
  text-align: center;
  color: var(--el-text-color-secondary);
}

.category-card {
  margin-bottom: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.category-icon {
  font-size: 36px;
  margin-bottom: 15px;
  color: var(--el-color-primary);
}

.category-card h3 {
  margin-bottom: 10px;
  font-size: 16px;
  flex-grow: 1;
}

.count {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: auto;
}

.content-list-container {
  margin-top: 20px;
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
  padding-left: 0;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.no-content {
  margin-top: 50px;
  text-align: center;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>